package com.pactera.madp.cp.service.sync.impl;

import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.pactera.madp.cp.api.entity.sync.SyncJobInfoEntity;
import com.pactera.madp.cp.common.constant.Constants;
import com.pactera.madp.cp.common.util.sync.SyncUtils;
import com.pactera.madp.cp.config.SyncConfig;
import com.pactera.madp.cp.context.SyncStateContext;
import com.pactera.madp.cp.mapper.sync.SyncJobInfoMapper;
import com.pactera.madp.cp.service.sync.SyncJobInfoHisService;
import com.pactera.madp.cp.service.sync.SyncJobInfoService;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.io.File;
import java.util.Date;
import java.util.List;

@Slf4j
@Service
@AllArgsConstructor
public class SyncJobInfoServiceImpl extends ServiceImpl<SyncJobInfoMapper, SyncJobInfoEntity> implements SyncJobInfoService {

    private final SyncJobInfoHisService syncJobInfoHisService;
    private final SyncConfig syncConfig;

    @Override
    public void addYesterdayToHis() {
        log.debug("岗位信息：addYesterdayToHis");
        String date = DateUtil.format(new Date(), Constants.DATE_FORMAT);
        syncJobInfoHisService.syncOneDay(date);
    }

    @Override
    public void deleteYesterday() {
        log.debug("岗位信息：deleteYesterday");
        this.remove(Wrappers.emptyWrapper());
    }

    @Override
    public void parse() {
        log.debug("岗位信息：parse");
        DateTime offsetDay = DateUtil.offsetDay(new Date(), -1);
        String fileDate = DateUtil.format(offsetDay, Constants.DATE_FORMAT);
        String filepath = SyncUtils.buildFilePath(syncConfig.getHrPath(), Constants.FN_JOB, fileDate);
        File newestFile = SyncUtils.getNewestFile(filepath);

        List<SyncJobInfoEntity> entityList
                = SyncUtils.parse(newestFile, Constants.SEPARATOR_STX, SyncJobInfoEntity.class, syncConfig.getHrCharset());
        this.saveBatch(entityList);
    }

    @Override
    public void deleteHisOneDay() {
        log.debug("岗位信息：deleteHisOneDay");
        DateTime offsetDay = DateUtil.offsetDay(new Date(), -30);
        String date = DateUtil.format(offsetDay, Constants.DATE_FORMAT);
        syncJobInfoHisService.deleteOneDate(date);
    }

    @Override
    public void syncBusiness() {
        log.debug("岗位信息：syncBusiness");
        SyncStateContext.get().setFinalState(true);
    }

}